﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Trackr.Core.Entities;
using System.Reflection;

namespace Trackr.Core
{
	public class Trackr
	{
		private static object _lock = new object();
		private static Trackr _instance;
		private TrackrDataHandler _dataHandler;
		public static Trackr Instance
		{
			get
			{
				lock (_lock)
				{
					if (_instance == null)
						_instance = new Trackr();
					return _instance;
				}
			}
		}
		private Trackr()
		{
			_dataHandler = new TrackrDataHandler();
		}
		public Model.TimeItem GetTimeItem(int id)
		{
			return _dataHandler.Get(id);
		}
		public Model.TimeItem GetLatestTimeItem()
		{
			return _dataHandler.GetAll().OrderBy(t => t.Id).FirstOrDefault();
		}
		public IEnumerable<Model.TimeItem> GetTimeItems(DateTime startDate, DateTime endDate)
		{
			return _dataHandler.GetAll(startDate, endDate);
		}
		public int AddNew(Model.TimeItem itemToSave)
		{
			_dataHandler.Save(itemToSave);
			return 1;
		}
		public int AddNew(string txt)
		{
			var ti = new Model.TimeItem
			{
				Duration = new TimeSpan(),
				StartTime = DateTime.Now,
				Task = txt
			};
			_dataHandler.Save(ti);
			return 1;
		}
		public void Update(Model.TimeItem itemToUpdate, Model.TimeItem itemData)
		{
			_dataHandler.Save(itemData);
		}
		public void Update(int itemId, Model.TimeItem itemData)
		{
			_dataHandler.Save(itemData);
		}
		public void ClearData()
		{
			//_trackrDataTable.Truncate();
		}

		public void StopCurrentTimeItem()
		{
			var ti = this.GetLatestTimeItem();
			ti.Duration = DateTime.Now.Subtract(ti.StartTime);
			this.Update(ti.Id, ti);
		}
	}
}
